<script setup lang="ts" name="User">
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { checkPermission } from '@/utils/permission'
import { warnBox } from '@/utils/utils'
import { getDicts } from '@/api/system/dict/index'
import type { User } from '@/api/system/user/type'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { formatDate } from '@/utils/day'
import { allocatedUserList, authUserCancelAll } from '@/api/system/role'
import AddUser from './components/AddUser.vue'
import { useTagsViewStore } from '@/store/tagsView'

const route = useRoute()
const sysNormalDisable = ref<IGetDictsRes>([])
const selectList = ref<number[]>([])
const tagsViewStore = useTagsViewStore()
const router = useRouter()
// form
const formValue = ref({
	userName: '',
	phoneNumber: ''
})

const formOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '用户名称',
		prop: 'userName'
	},

	{
		type: 'input',
		label: '手机号码',
		prop: 'phoneNumber'
	}
])

// table
const loading = ref(false)
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})
const tableData = ref<User[]>([])
const columns = ref<TableColums[]>([
	{
		type: 'selection',
		align: 'center'
	},
	{
		label: '用户名称',
		prop: 'userName'
	},
	{
		label: '用户昵称',
		prop: 'nickName'
	},
	{
		label: '邮箱',
		prop: 'email'
	},
	{
		label: '手机',
		prop: 'phoneNumber'
	},
	{
		label: '状态',
		prop: 'status'
	},
	{
		label: '创建时间',
		prop: 'createTime',
		formatter: v => formatDate(v.createTime)
	},
	{
		prop: 'action',
		fixed: 'right',
		label: '操作',
		width: '140px',
		align: 'center'
	}
])
// dialog
const addUserRef = useTemplateRef('addUserRef')
const roleId = computed(() => route.params.roleId as string)

const getTableData = async () => {
	try {
		loading.value = true
		const params = {
			pageNum: page.value.currentPage,
			pageSize: page.value.pageSize,
			roleId: roleId.value,
			...formValue.value
		}
		const res = await allocatedUserList(params)
		tableData.value = res.data.rows
		page.value.total = res.data.total
	} finally {
		loading.value = false
	}
}
const handleSelectionChange = (val: User[]) => {
	selectList.value = val.map(v => v.id)
}
const handelAdd = () => {
	addUserRef.value?.init()
}

const cancelAuthUserAll = () => {
	// 批量取消授权
	const userIds = selectList.value.join(',')
	handelDelete(userIds)
}
const handelDelete = async (userIds: string) => {
	const roleId = route.params.roleId as string
	await warnBox({
		title: '提示',
		message: `是否取消选中用户授权数据项?`
	})
	await authUserCancelAll({
		roleId,
		userIds
	})
	ElMessage.success('删除成功')
	getTableData()
}
const handelClose = () => {
	// 关闭页面
	tagsViewStore.delView({
		path: route.path,
		name: route.name as string
	})
	router.replace('/system/role')
}

const init = async () => {
	await getDicts('sys_sys_normal_disable').then(data => {
		sysNormalDisable.value = data
	})
}

onMounted(() => {
	init()
	getTableData()
})
</script>

<template>
	<div class="table-page-box">
		<div class="filter-box">
			<QForm
				inline
				:model="formValue"
				:form-options="formOptions"
				:buttons="['search', 'reset']"
				@search="getTableData"
				@reset="getTableData"
			/>
		</div>
		<div class="table-box">
			<QTable
				:data="tableData"
				:columns="columns"
				:page="page"
				:loading="loading"
				style="width: 100%"
				@pageChange="getTableData"
				@selectionChange="handleSelectionChange"
			>
				<template #headerLeft>
					<el-button
						v-if="checkPermission(['system:role:add'])"
						type="primary"
						@click="handelAdd"
					>
						添加用户
					</el-button>
					<el-button
						v-if="checkPermission(['system:role:remove'])"
						:disabled="!(selectList.length > 0)"
						@click="cancelAuthUserAll"
					>
						批量取消授权
					</el-button>
					<el-button @click="handelClose"> 关闭 </el-button>
				</template>
				<template #action="{ row }">
					<el-button
						v-if="checkPermission(['system:role:remove']) && row.userId !== 1"
						type="primary"
						link
						@click="handelDelete(row.id)"
					>
						取消授权
					</el-button>
				</template>
				<template #status="{ row }">
					<DictTag
						:value="row.status"
						:options="sysNormalDisable"
					/>
				</template>
			</QTable>
		</div>
		<AddUser
			ref="addUserRef"
			:role-id="roleId"
			@refresh="getTableData"
		/>
	</div>
</template>
